﻿using jlynet.core.Library;
using jlynet.core.notebook.model;
using jlynet.core.notebook.myform;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace jlynet.core.notebook.util
{
    public class TreeViewHelper
    {
        private static TreeView treeView;
        private static TreeViewHelper treeViewHelper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="listViewName"></param>
        /// <param name="form"></param>
        public TreeViewHelper(string treeViewName, Form form)
        {
            if (treeView == null)
            {
                treeView = getTreeView(treeViewName, form);
            }
        }

        /// <summary>
        /// treeView 设置方法
        /// </summary>
        /// <param name="treeViewName"></param>
        /// <param name="form"></param>
        public static TreeViewHelper setTreeView(string treeViewName, Form form)
        {
            if (treeViewHelper == null)
            {
                treeViewHelper = new TreeViewHelper(treeViewName, form);
            }
            return treeViewHelper;
        }

        public TreeView getTreeView(string treeViewName, Form form)
        {
            try
            {
                return (TreeView)(form.Controls.Find(treeViewName, false)[0]);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 绑定sqlite的数据
        /// </summary>
        public void SelectData()
        {
            AddTreeView(0, (TreeNode)null);
        }

        /// <summary>
        /// 查询sqlite的数据，然后绑定到treeview控件
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="parentNode"></param>
        public void AddTreeView(int parentId, TreeNode parentNode)
        {
            try
            {
                string sql = "select * from directoryDataTable";
                //SQLiteConfigHelper.DatabaseFile = SysHelper.GetStartupPath() + "\\222.jlynet";
                DataView dv = MySQLiteHelper.SelectDataView(sql,new SQLiteParameter[] { });
                string strFile = "pid=" + parentId;
                dv.RowFilter = strFile;

                foreach (DataRowView row in dv)
                {
                    TreeNode node = new TreeNode();
                    node.ImageIndex = 0;//imagelist中的图片索引,设置节点图片
                    //node.BackColor = Color.Red;//背景颜色
                    //处理根节点
                    if (parentId == 0)
                    {
                        node.Name = row["id_"].ToString();
                        node.Text = row["name_"].ToString();
                        node.Tag = row;
                        treeView.Nodes.Add(node);

                        AddTreeView(Int32.Parse(row["id_"].ToString().Trim()), node);
                    }
                    else
                    { //处理子节点
                        node.Name = row["id_"].ToString();
                        node.Text = row["name_"].ToString();
                        node.Tag = row;
                        parentNode.Nodes.Add(node);

                        AddTreeView(Int32.Parse(row["id_"].ToString().Trim()), node);
                    }
                }
                treeView.ExpandAll();
            }
            catch { }
        }

        /// <summary>
        /// 修改treeview结构，保存到sqlite，这几个函数和使用MSSQL是一样的，
        /// 和ADO.NET很像，所以这里也就直接贴出代码了，欢迎私下讨论。
        /// </summary>
        public void ModifyTreeView()
        {
            try
            {
                string new_node_name = null;
                string node_id = null;
                //string node_name = null;
                treeView.AfterLabelEdit += (s, e) => {
                    string id = e.Node.Name;
                    string name = e.Node.Text;
                    new_node_name = e.Label;
                    if (!StringHelper.IsNullOrEmpty(new_node_name))
                    {
                        node_id = id;
                        string sql = string.Empty;
                        if (StringHelper.IsNullOrEmpty(new_node_name))
                        {
                            MessageBox.Show("请输入目录名称!", "提示");
                            return;
                        }
                        
                        sql = "update directoryDataTable set name_='" + new_node_name + "' where id_='" + node_id + "'";
                            MySQLiteHelper.executionSQL(sql);
                        e.Node.Text = new_node_name;
                        //treeView.Nodes.Clear();
                        //AddTreeView(treeView, 0, (TreeNode)null);
                    }
                };
            }
            catch { }
        }

        /// <summary>
        ///  删除节点，这里有个情况，如果删除多个，就是删除的节点中还有子节点的话，
        ///  该如何操作，是把当前选中节点全部删掉，还是让用户只删除一个，这就看个人的需求了，
        ///  我项目中的是只让客户删除不超过2级的节点。
        /// </summary>
        public void RemoveTreeView()
        {
            try
            {
                if (treeView.SelectedNode != null)
                {
                    TreeNode node = treeView.SelectedNode;
                    int childNode = node.Nodes.Count;
                    if (childNode == 0)
                    {
                        DeleteTreeNode(node);
                    }
                    else
                    {
                        if (MessageBox.Show("确定要删除选中的所有节点吗 ？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            DeleteTreeNode(node);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("未选中节点，请选中需要删除的节点！", "提示");
                }
            }
            catch (Exception ex)
            {

                
            }
        }


        /// <summary>
        /// 删除所选节点及其子节点，同时更新数据库
        /// </summary>
        /// <param name="parentNode"></param>
        public static void DeleteTreeNode(TreeNode parentNode)
        {
            try
            {
                //获取当前删除的节点是否还有子节点
                int childCount = parentNode.Nodes.Count;
                for (int i = 0; i < childCount; i++)
                {
                    TreeNode childNode = parentNode.Nodes[0];
                    if (childNode.Nodes.Count > 0)
                    {
                        DeleteTreeNode(childNode);
                    }
                    else
                    {
                        DeleteTreeNode(childNode);
                        childNode.Remove();
                    }
                }
                if (parentNode.Nodes.Count == 0)
                {
                    DeleteNodeData(parentNode);
                    parentNode.Remove();
                }
            }
            catch { }
        }

        /// <summary>
        /// 在数据库中删除当前选中的节点
        /// </summary>
        /// <param name="node"></param>
        public static void DeleteNodeData(TreeNode node)
        {
            try
            {
                string sql = string.Empty;
                sql = "delete from directoryDataTable where id_=" + node.Name + "";
                MySQLiteHelper.executionSQL(sql);
                sql = "delete from entryDataTable where directory_id=" + node.Name + "";
                MySQLiteHelper.executionSQL(sql);
            }
            catch (Exception ex)
            {

               
            }
        }

        /// <summary>
        /// 获得选取好的节点
        /// </summary>
        /// <param name="treeView"></param>
        /// <returns></returns>
        public DirectoryDataTableModel GetSelectedNode()
        {
            try
            {
                TreeNode selectedFatherNode = treeView.SelectedNode; //获得被选中的根节点
                //while (selectedFatherNode != null){
                //    TreeNode childNode = null; //根节点的被选中的子节点
                //    childNode = selectedFatherNode.FirstNode;
                //    while (childNode != null){//找该节点的所有被选择的子节点
                //        if (childNode.Checked){
                //            //处理数据
                //            
                //        }
                //        childNode = childNode.NextNode;
                //    }
                //    selectedFatherNode = selectedFatherNode.NextNode; //下一个被选中的章节节点
                //}
                DirectoryDataTableModel model = new DirectoryDataTableModel();
                model.id = selectedFatherNode.Name;
                model.name = selectedFatherNode.Text;
                DataRowView row = (DataRowView)selectedFatherNode.Tag;
                if (row != null)
                {
                    model.type = row["type_"] != DBNull.Value ? row["type_"].ToString() : "0";
                }
                return model;
            }
            catch (Exception ex)
            {
            }
            return null;
        }



        //TreeVIew清空
        public static void listViewClear(TreeView treeView)
        {
            try
            {
                treeView.Nodes.Clear();  //从控件中移除所有项和列（包括列表头）。
            }
            catch (Exception ex)
            {

                
            }
        }



    }
}
